package com.mti.zhpt.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mti.zhpt.constant.TargetMap;
import com.mti.zhpt.dao.EventMapper;
import com.mti.zhpt.model.*;
import com.mti.zhpt.shared.Exception.BusinessException;
import com.mti.zhpt.shared.websocket.EventWebSocket;
import com.mti.zhpt.utils.DateUtil;
import com.mti.zhpt.utils.SnowFlake;
import com.mti.zhpt.vo.EventRequestDTO;
import com.mti.zhpt.vo.PageDTO;
import com.mti.zhpt.vo.SystemPersonVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.mti.zhpt.utils.Constant;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 案事件
 * @Author: zhaopf@mti-sh.cn
 * @Date: 2019/4/18 11:14
 */
@Service("eventServiceImpl")
@Slf4j
public class EventServiceImpl {
	public static final String SJ_ROLE_TYPE = "1";
	public static final String FJ_ROLE_TYPE = "2";
	public static final String PCS_ROLE_TYPE= "3";

	@Autowired
	private SnowFlake snowFlake;

	@Resource
	private EventMapper eventMapper;

	@Autowired
	ResourceServiceImpl resourceService;

	@Autowired
	private EventDetailsServiceImpl eventDetailsService;



	RestTemplate restTemplate;

	//注入 RestTemplateBuilder
	@Autowired
	private void initRestTemplate(RestTemplateBuilder builder) {
		this.restTemplate = builder.build();
	}

	@Autowired
	EventTimerServiceImpl eventTimerService;

	@Autowired
	EventTimerFileServiceImpl eventTimerFileService;

	@Value("${fastDetail.systemUrl}")
	private String fastDetailSystemUrl;

	@Value("${fastDetail.content}")
	private String fastDetailContent;

	/**
	 * @Description:
	 * @Author: zhaopf@mti-sh.cn
	 * @Date: 2019/4/18
	 */
	public List<Map<String, Object>> queryList(EventEntity entity) {
		List<Map<String, Object>> result = null;
		try {
			result = eventMapper.queryList(entity);
			for (Map<String, Object> res : result) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @Description:查询周边资源
	 * @Author: yingjj@mti-sh.cn
	 * @Date: 2019/4/26
	 */
	public Map<String, Object> queryNearBy(String event_id, Integer dis, boolean orderbydis) {
		List<Map<String, Object>> resultEvents = null;
		List<Map<String, Object>> resultJurisdictions = null;
		List<Map<String, Object>> resultPolices = null;
		List<Map<String, Object>> resultMoniters = null;
		List<Map<String, Object>> resultTrafficcheckpoints = null;
		List<Map<String, Object>> resultCompanys = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			resultEvents = eventMapper.queryNearByEvent(event_id, dis);
			for (Map<String, Object> res : resultEvents) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			resultTrafficcheckpoints = eventMapper.queryNearByTrafficcheckpoint(event_id, dis);
			for (Map<String, Object> res : resultTrafficcheckpoints) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			resultJurisdictions = eventMapper.queryNearByJurisdictionsFake(event_id, dis);
			for (Map<String, Object> res : resultJurisdictions) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			resultPolices = eventMapper.queryNearByPolices(event_id, dis,orderbydis);
			for (Map<String, Object> res : resultPolices) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			resultMoniters = eventMapper.queryNearByMoniters(event_id, dis);
			for (Map<String, Object> res : resultMoniters) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			resultCompanys = eventMapper.queryNearByCompanys(event_id, dis);
			for (Map<String, Object> res : resultCompanys) {
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> companys = (List<Map<String, Object>>) res.get("companys");
				for (Map<String, Object> com : companys) {
					Double[] coordinates = { (Double) com.get("longitude"), (Double) com.get("latitude") };
					com.put("coordinates", coordinates);
				}
			}
			result.put("Events", resultEvents);
			result.put("Jurisdictions", resultJurisdictions);
			result.put("Polices", resultPolices);
			result.put("Moniters", resultMoniters);
			result.put("Trafficcheckpoints", resultTrafficcheckpoints);
			result.put("Companys", resultCompanys);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

    /**
     * @Description:查询周边资源
     * @Author: yingjj@mti-sh.cn
     * @Date: 2019/4/26
     */
    public Map<String, Object> queryNearByType(String event_id, Integer dis, boolean orderbydis, String type) {

        Map<String, Object> result = new HashMap<String, Object>();

        if (type.equals("Events")) {
            List<Map<String, Object>> resultEvents = null;
            try {
                resultEvents = eventMapper.queryNearByEvent(event_id, dis);
                for (Map<String, Object> res : resultEvents) {
                    Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
                    res.put("coordinates", coordinates);
                }
                result.put("Events", resultEvents);
            } catch (Exception e) {
            }
        } else if (type.equals("Jurisdictions")) {
            List<Map<String, Object>> resultJurisdictions = null;
            try {
                resultJurisdictions = eventMapper.queryNearByJurisdictionsFake(event_id, dis);
                for (Map<String, Object> res : resultJurisdictions) {
                    Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
                    res.put("coordinates", coordinates);
                }
                result.put("Jurisdictions", resultJurisdictions);
            } catch (Exception e) {
            }

        } else if (type.equals("Polices")) {
            List<Map<String, Object>> resultPolices = null;
            try {
                resultPolices = eventMapper.queryNearByPolices(event_id, dis,orderbydis);
                for (Map<String, Object> res : resultPolices) {
                    Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
                    res.put("coordinates", coordinates);
                }
                result.put("Polices", resultPolices);
            } catch (Exception e) {
            }
        } else if (type.equals("Moniters")) {
            List<Map<String, Object>> resultMoniters = null;
            try {
                resultMoniters = eventMapper.queryNearByMoniters(event_id, dis);
                for (Map<String, Object> res : resultMoniters) {
                    Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
                    res.put("coordinates", coordinates);
                }
                result.put("Moniters", resultMoniters);
            } catch (Exception e) {
            }

        } else if (type.equals("Trafficcheckpoints")) {

            List<Map<String, Object>> resultTrafficcheckpoints = null;
            try {
                resultTrafficcheckpoints = eventMapper.queryNearByTrafficcheckpoint(event_id, dis);
                for (Map<String, Object> res : resultTrafficcheckpoints) {
                    Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
                    res.put("coordinates", coordinates);
                }
                result.put("Trafficcheckpoints", resultTrafficcheckpoints);
            } catch (Exception e) {
            }
        } else if (type.equals("Companys")) {

            List<Map<String, Object>> resultCompanys = null;
            try {
                resultCompanys = eventMapper.queryNearByCompanys(event_id, dis);
                for (Map<String, Object> res : resultCompanys) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> companys = (List<Map<String, Object>>) res.get("companys");
                    for (Map<String, Object> com : companys) {
                        Double[] coordinates = { (Double) com.get("longitude"), (Double) com.get("latitude") };
                        com.put("coordinates", coordinates);
                    }
                }
                result.put("Companys", resultCompanys);
            } catch (Exception e) {
            }
        } else {
            result = this.queryNearBy(event_id, dis, orderbydis);
        }
        return result;
    }

	/**
	 * @Description:查询周边警员并排序
	 * @Author: yingjj@mti-sh.cn
	 * @Date: 2019/4/26
	 */
	public Map<String, Object> queryNearByPolices(String event_id, Integer dis, boolean orderbydis) {
		List<Map<String, Object>> resultPolices = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
				resultPolices = eventMapper.queryNearByPolices(event_id, dis,orderbydis);
			for (Map<String, Object> res : resultPolices) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			result.put("Polices", resultPolices);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return result;
	}

	public int updateEventStatus(String eventId,Integer status) {
		int result = eventMapper.updateEventStatus(eventId, status, new Date());
		return result;
	}

	public Map<String, Object> addEvent(Map<String, Object> event) {
		event.put("eventId", snowFlake.nextId());
		eventMapper.addEvent(event);
		return event;
	}

	/**
	 * 添加新警情
	 *
	 * @param event 警情信息對象
	 * @return
	 */
	public EventEntity addEventByEventEntity(EventEntity event) {
		event.setEventId(snowFlake.nextId());
		eventMapper.addEventByEventEntity(event);

		CpPerson cpPerson = new CpPerson();
		cpPerson.setId(snowFlake.nextId());
		cpPerson.setName(event.getPoliceMan());
		cpPerson.setPhone(event.getPhone());
		eventMapper.insertPerson(cpPerson);

		eventMapper.insertEventPersonnel(event.getEventId(), cpPerson.getId(), "报案人");
		return event;
	}

	public List<Map<String, Object>> listByPrams(EventQueryPram eventQueryPram) {
		List<Map<String, Object>> result = null;
		try {
			result = eventMapper.listByPrams(eventQueryPram);
			for (Map<String, Object> res : result) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public int delEventNewCreated(String mineventId) {
		return eventMapper.delEventNewCreated(mineventId);
	}

	public void pushEventNewCreated() {
		try {
			Map<String, Object> event = eventMapper.queryNewestEvent();
			event.put("msgType",Constant.MSG_EVENT);
			EventWebSocket.sendInfo(event);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public PageInfo pageByEvent(EventEntity event) {
		PageInfo pageInfo = null;
		try {
			if(event.getDeptLevel().equals("2")|| event.getDeptLevel().equals("3")){
				if (StringUtils.isEmpty(event.getDeptCode())){
					throw new BusinessException("登录人id NOT NULL");
				}else if (StringUtils.isEmpty(event.getDeptLevel())){
					throw new BusinessException("登录人数据权限级别 NOT NULL");
				}
			}
			if (event.getDeptLevel().equals("2")){
				event.setDeptCode(event.getDeptCode().substring(0,6)+"000000");
			}

		PageHelper.startPage(event.getPageNum(), event.getPageSize());
		List<Map<String, Object>> result = null;

			result = eventMapper.queryList(event);
			for (Map<String, Object> res : result) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
			pageInfo = new PageInfo(result);
		} catch (Exception e) {
			log.error("警情列表",e);
			throw new BusinessException(e.getMessage());
		}
		return pageInfo;
	}

	/**
	 * 根据时间查询案件event_id, longitude,latitude,level
	 *
	 * @param entity
	 * @return
	 */
	public List<Map<String, Object>> listByEvent(EventEntity entity) {
		List<Map<String, Object>> result = null;
		try {
			result = eventMapper.listByEvent(entity);
			for (Map<String, Object> res : result) {
				Double[] coordinates = { (Double) res.get("longitude"), (Double) res.get("latitude") };
				res.put("coordinates", coordinates);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 快速处置
	 *
	 * @param token 登录者
	 * @param event 警情信息對象
	 * @return
	 */
	public void fastDetail(String token, EventEntity event) {
		/*
		## 测试数据
		// 用户token
		token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwNzUwMDEiLCJqdGkiOiJkYW9zaHUiLCJpYXQiOjE1NjU2MDY1NzcsImlzcyI6Imh0dHA6Ly9kYW9zaHUuY29tIn0.L7-BepMi428nSbDio4TPEBg1noCe__lD8H4kevfROvaedO2f08aSZQp2gsrSZvbk129hO3zdarkcnlRnQqghtQ";
		event.setEventId("13100020190529101118000028");
		event.setAddress("燕郊星河皓月22楼楼2单元603");
		event.setUnitPoliceId("075001");
		event.setUnitPoliceName("赵晋进");
		*/

		// 消息内容
		String content = fastDetailContent;

		// 快速处置
		List<String> arroundPolices = new ArrayList<>();

		List<Double> center = new ArrayList<>();
		center.add(event.getLongitude());
		center.add(event.getLatitude());
		Map<String, Object> properties = new HashMap<>();
		properties.put("pageid", 1);
		properties.put("pagesize", 99999);
		// 设置圈选属性
		Circle circle = new Circle();
		circle.setProperties(properties);
		circle.setType("Circle");
		circle.setCenter(center);
		circle.setRadius(Double.valueOf("1000.00"));
		Map<String, Object> circleResult = resourceService.queryCircle(circle);
		if (!circleResult.isEmpty()) {
			if (null != circleResult.get("data")) {
				List<Map<String, Object>> data = (List<Map<String, Object>>) circleResult.get("data");
				if (null != data) {
					for (Map<String, Object> result: data) {
						String kind = (String) result.get("kind");
						if (kind.equals("police")) {
							arroundPolices.add(String.valueOf(result.get("title")));
						}
					}
				}
			}
		}

		List<SystemPersonVo> policeList = new ArrayList<>();

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("Authorization", token);
		String requestBody = "";
		HttpEntity<String> requestEntity = new HttpEntity<String>(requestBody, headers);
		List<SystemPersonVo> systemPersonVoList = new ArrayList<>();
		ResponseEntity result = restTemplate.postForEntity(fastDetailSystemUrl + "/api/system/person/lists", requestEntity, String.class);
		if (null != result) {
			if (null != result.getBody()) {
				JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
				if (jsonObject.containsKey("data")) {
					systemPersonVoList = JSONArray.parseArray(jsonObject.getString("data"), SystemPersonVo.class);
				}
			}
		}

		List<EventTimerEntity> eventTimerEntityList = new ArrayList<>();

		for (String policeName : arroundPolices) {
			for (SystemPersonVo  systemPersonVo : systemPersonVoList) {
				if (policeName.equals(systemPersonVo.getName())) {
					policeList.add(systemPersonVo);

					EventTimerEntity eventTimerEntity = new EventTimerEntity();
					eventTimerEntity.setEventId(event.getEventId());
					eventTimerEntity.setFeedback("下达指令");
					eventTimerEntity.setCreateTime(new Date());
					eventTimerEntity.setStatus((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YXD));
					eventTimerEntity.setRemark(content);
					eventTimerEntity.setDeptName(systemPersonVo.getOrgName());
					eventTimerEntity.setPoliceName(systemPersonVo.getName());
					eventTimerEntity.setPoliceCode(systemPersonVo.getId());
					eventTimerEntityList.add(eventTimerEntity);
					break;
				}
			}
		}

		eventTimerService.insertEventTimerBatch(eventTimerEntityList);

		for (SystemPersonVo police : policeList) {
			List<String> members = new ArrayList<>();
			members.add(event.getUnitPoliceId());
			members.add(police.getId());

			String title = event.getAddress() + "-" + event.getUnitPoliceName() + "、" + police.getName();

			Map<String, Object> microGroupBusiness = new HashMap<>();
			microGroupBusiness.put("businessId", event.getEventId());
			microGroupBusiness.put("businessType", 2);

			Map<String, Object> microGroup = new HashMap<>();
			microGroup.put("groupType", "2");
			microGroup.put("members", members);
			microGroup.put("title", title);
			microGroup.put("business", true);
			microGroup.put("microGroupBusiness", microGroupBusiness);

			String addMicroGroupBody = JSONObject.toJSONString(microGroup);
			HttpEntity<String> requestAddMicroGroupBody = new HttpEntity<>(addMicroGroupBody, headers);
			ResponseEntity addMicroGroupResult = restTemplate.postForEntity(fastDetailSystemUrl + "/api/message/mds/microGroup", requestAddMicroGroupBody, String.class);
			if (null != addMicroGroupResult) {
				if (null != addMicroGroupResult.getBody()) {
					JSONObject jsonObject = JSONObject.parseObject(addMicroGroupResult.getBody().toString());
					if (jsonObject.containsKey("data")) {
						JSONObject data = jsonObject.getJSONObject("data");
						if (!data.isEmpty()) {
							System.out.println(data);

							Map<String, Object> message = new HashMap<>();
							message.put("type", 0);
							message.put("content", content);
							message.put("microGroupId", data.getString("id"));
							String sendMessageBody = JSONObject.toJSONString(message);
							HttpEntity<String> requestSendMessageBody = new HttpEntity<>(sendMessageBody, headers);
							ResponseEntity sendMessageResult = restTemplate.postForEntity(fastDetailSystemUrl + "/api/message/mds/microGroup/message", requestSendMessageBody, String.class);
						}
					}
				}
			}
		}
	}

	/**
	 * 日常警情升级为重大警情
	 *
	 * @param event 警情对象
	 * @return
	 */
	public boolean upgradeImportEvent(EventEntity event) {
		Integer result = eventMapper.upgradeImportEvent(event);
		return null != result && result >= 1;
	}

	public int updateSendTime(String eventid, Date sendTime) {
		return eventMapper.updateSendTime(eventid, sendTime);
	}

	/**
	 * 警情反馈补充
	 *
	 * @param eventTimerEntity 时间轴对象
	 * @return
	 */
	public boolean insertEventTimer(EventTimerEntity eventTimerEntity) {
		if (StringUtils.isBlank(eventTimerEntity.getFeedback())) {
			eventTimerEntity.setFeedback("反馈");
			eventTimerEntity.setStatus(100);
		}

		eventTimerEntity.setCreateTime(new Date());
		Boolean result = eventTimerService.insertEventTimer(eventTimerEntity);
		eventTimerFileService.saveEventTimerFileBatch(eventTimerEntity);
		return result;
	}

	public PageDTO<EventEntity> listByPage(EventRequestDTO dto){
		PageDTO<EventEntity> pageDTO = new PageDTO<>();
		dto.setStart(dto.getStart()<=0?0:dto.getStart()-1);
		List<String> callPoliceTypes = Arrays.asList(dto.getCallPoliceType().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> eventStatus = Arrays.asList(dto.getEventStatus().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> personType = Arrays.asList(dto.getPersonType().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> range = Arrays.asList(dto.getRange().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> isControl = Arrays.asList(dto.getIsControl().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> personLevel = Arrays.asList(dto.getPersonLevel().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> zrbm = Arrays.asList(dto.getZrbm().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> ryly = Arrays.asList(dto.getRyly().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		String overTimeDate = "";
		if (StringUtils.isNotBlank(dto.getIsOverTime()) && dto.getIsOverTime().equals("1")) {
			long currentTime = System.currentTimeMillis() - 150 * 60 * 1000;
			overTimeDate = DateUtil.formatDate(new Date(currentTime),"datetime");
		}
		List<EventEntity> list = eventMapper.listByPage(
				callPoliceTypes,
				eventStatus,
				personType,
				zrbm,
				isControl,
				personLevel,
				range,
				dto.getRangeType(),
				dto.getStartDate(),
				dto.getEndDate(),
				dto.getStart(),
				dto.getSize(),
				dto.getEventType(),
				dto.getPoliceId(),
				dto.getSearchTerm(),
				overTimeDate,
				ryly
		);
		list.parallelStream().forEach(item->{
			if(StringUtils.isEmpty(item.getAddress()))
				item.setAddress("暂无地址");
		});
		pageDTO.setRecord(list);
		pageDTO.setTotal(
				eventMapper.countListByPage(
						callPoliceTypes,
						eventStatus,
						personType,
						zrbm,
						isControl,
						personLevel,
						range,
						dto.getRangeType(),
						dto.getStartDate(),
						dto.getEndDate(),
						dto.getEventType(),
						dto.getPoliceId(),
						dto.getSearchTerm(),
						overTimeDate,
						ryly
				)
		);
		return pageDTO;
	}

	public PageDTO<EventEntity> listByPageV2(EventRequestDTO dto){
		PageDTO<EventEntity> pageDTO = new PageDTO<>();
		dto.setStart(dto.getStart()<=0?0:dto.getStart()-1);

		List<String> callPoliceTypes = Arrays.asList(dto.getCallPoliceType().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> eventStatus = Arrays.asList(dto.getEventStatus().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> personType = Arrays.asList(dto.getPersonType().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> range = Arrays.asList(dto.getRange().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> isControl = Arrays.asList(dto.getIsControl().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> personLevel = Arrays.asList(dto.getPersonLevel().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> zrbm = Arrays.asList(dto.getZrbm().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> ryly = Arrays.asList(dto.getRyly().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		String overTimeDate = "";
		if (StringUtils.isNotBlank(dto.getIsOverTime()) && dto.getIsOverTime().equals("1")) {
			long currentTime = System.currentTimeMillis() - 150 * 60 * 1000;
			overTimeDate = DateUtil.formatDate(new Date(currentTime),"datetime");
		}
		List<EventEntity> list = eventMapper.listByPageV2(
				callPoliceTypes,
				eventStatus,
				personType,
				zrbm,
				isControl,
				personLevel,
				range,
				dto.getRangeType(),
				dto.getStartDate(),
				dto.getEndDate(),
				dto.getStart(),
				dto.getSize(),
				dto.getEventType(),
				dto.getPoliceId(),
				dto.getSearchTerm(),
				overTimeDate,
				ryly
		);
		list.parallelStream().forEach(item->{
			if(StringUtils.isEmpty(item.getAddress()))
				item.setAddress("暂无地址");
		});

		List<EventEntity> filterList = new ArrayList<>();
		switch (dto.getRangeType()) {
			case SJ_ROLE_TYPE:
				filterList.addAll(list);
				break;
			case FJ_ROLE_TYPE:
				String userOrgId = dto.getUserOrgId();
				if(StringUtils.isNotBlank(userOrgId)) {
					userOrgId = userOrgId.substring(0, 6);
				}
				String userZrbm = dto.getUserZrbm();
				for (EventEntity eventEntity : list) {
					if(StringUtils.isNotBlank(userZrbm)) {
						if(eventEntity.getZrbm().equals(userZrbm)) {
							if (StringUtils.isNotBlank(userOrgId)) {
								if (eventEntity.getBranchUnitId().substring(0, 6).equals(userOrgId)) {
									filterList.add(eventEntity);
								}
							}
						}
					} else {
						if (StringUtils.isNotBlank(userOrgId)) {
							if (eventEntity.getBranchUnitId().substring(0, 6).equals(userOrgId)) {
								filterList.add(eventEntity);
							}
						}
					}
				}
				break;
			case PCS_ROLE_TYPE:
				filterList.addAll(list);
				break;
			default:
				filterList.addAll(list);
				break;
		}

		pageDTO.setRecord(filterList);
		pageDTO.setTotal(
				eventMapper.countListByPage(
						callPoliceTypes,
						eventStatus,
						personType,
						zrbm,
						isControl,
						personLevel,
						range,
						dto.getRangeType(),
						dto.getStartDate(),
						dto.getEndDate(),
						dto.getEventType(),
						dto.getPoliceId(),
						dto.getSearchTerm(),
						overTimeDate,
						ryly
				)
		);
		return pageDTO;
	}

	public PageDTO<EventEntity> listByPageV3(EventRequestDTO dto){
		if(dto.getEventType().equals("0") || dto.getEventType().equals("2")) {
			return listByPage(dto);
		}

		PageDTO<EventEntity> pageDTO = new PageDTO<>();
		dto.setStart(dto.getStart()<=0?0:dto.getStart()-1);

		List<String> callPoliceTypes = Arrays.asList(dto.getCallPoliceType().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> eventStatus = Arrays.asList(dto.getEventStatus().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> personType = Arrays.asList(dto.getPersonType().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> range = Arrays.asList(dto.getRange().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> isControl = Arrays.asList(dto.getIsControl().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> personLevel = Arrays.asList(dto.getPersonLevel().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> zrbm = Arrays.asList(dto.getZrbm().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		List<String> ryly = Arrays.asList(dto.getRyly().split(",")).parallelStream().filter(StringUtils::isNoneEmpty).collect(Collectors.toList());
		String overTimeDate = "";
		if (StringUtils.isNotBlank(dto.getIsOverTime()) && dto.getIsOverTime().equals("1")) {
			long currentTime = System.currentTimeMillis() - 150 * 60 * 1000;
			overTimeDate = DateUtil.formatDate(new Date(currentTime),"datetime");
		}

		String userOrgId = "";
		String userZrbm = "";
		switch (dto.getUserType()) {
			case SJ_ROLE_TYPE:
				break;
			case FJ_ROLE_TYPE:
				userOrgId = dto.getUserOrgId();
				if(StringUtils.isNotBlank(userOrgId)) {
					userOrgId = userOrgId.substring(0, 6);
				}
				userZrbm = dto.getUserZrbm();
				break;
			default:
				break;
		}

		List<EventEntity> list = eventMapper.listByPageV3(
				callPoliceTypes,
				eventStatus,
				personType,
				zrbm,
				isControl,
				personLevel,
				range,
				dto.getRangeType(),
				dto.getStartDate(),
				dto.getEndDate(),
				dto.getStart(),
				dto.getSize(),
				dto.getEventType(),
				dto.getPoliceId(),
				dto.getSearchTerm(),
				overTimeDate,
				ryly,
				userOrgId,
				userZrbm
		);
		list.parallelStream().forEach(item->{
			if(StringUtils.isEmpty(item.getAddress()))
				item.setAddress("暂无地址");
		});

		pageDTO.setRecord(list);
		pageDTO.setTotal(
				eventMapper.countListByPage(
						callPoliceTypes,
						eventStatus,
						personType,
						zrbm,
						isControl,
						personLevel,
						range,
						dto.getRangeType(),
						dto.getStartDate(),
						dto.getEndDate(),
						dto.getEventType(),
						dto.getPoliceId(),
						dto.getSearchTerm(),
						overTimeDate,
						ryly
				)
		);
		return pageDTO;
	}

	public Map statistics(String eventId) {
		List<Long> countList = null;
		HashMap<Object, Long> result = null;
		try {
			Map<Object, Object> mapResult = new HashMap<>();
			 result = new HashMap<>();
			countList = eventMapper.countData(eventId);
			eventDetailsService.sumPolice(eventId,mapResult);


			Long sumDispatchNumber = (Long) ((Map) mapResult.get("powers")).get("sumDispatchNumber")+
					(Long) ((Map) mapResult.get("powers")).get("sumReachNumber");
			int unitTask = ((List) mapResult.get("unitTask")).size();

			result.put("fnxx", countList.get(0));
			result.put("zlfk", countList.get(1));
			result.put("xdzl", countList.get(2));
			result.put("cdrc", sumDispatchNumber);
			result.put("cdcc", 0L);
			result.put("czdw", (long) unitTask);
		} catch (Exception e) {
			log.error("指挥回溯错误：",e);
		}

		return result;
	}
}
